package com.hello.system.service.impl;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.alibaba.fastjson.JSONObject;
import com.hello.common.core.constant.UserConstants;
import com.hello.common.core.utils.StringUtils;
import com.hello.common.security.utils.SecurityUtils;
import com.hello.system.domain.SysUser;
import com.hello.system.domain.dto.WxLoginRequest;
import com.hello.system.domain.dto.WxLoginResponse;
import com.hello.system.domain.dto.WxRegisterRequest;
import com.hello.system.service.IWxUserService;
import com.hello.system.service.ISysUserService;
import com.hello.system.utils.WxApiUtils;

import lombok.extern.slf4j.Slf4j;

import java.util.HashMap;
import java.util.Map;

/**
 * 微信用户服务实现类
 * 
 * @author hello
 */
@Slf4j
@Service
public class WxUserServiceImpl implements IWxUserService {
    
    @Autowired
    private WxApiUtils wxApiUtils;
    
    @Autowired
    private ISysUserService userService;
    
    /**
     * 微信小程序登录
     * 
     * @param loginRequest 登录请求参数
     * @return 登录结果
     */
    @Override
    public WxLoginResponse wxLogin(WxLoginRequest loginRequest) {
        log.info("微信小程序登录请求: {}", loginRequest);
        
        // 调用微信接口获取openid和session_key
        JSONObject sessionResult = wxApiUtils.code2Session(loginRequest.getCode());
        if (sessionResult == null) {
            log.error("获取微信session失败");
            return null;
        }
        
        // 打印用户信息到控制台（测试用）
        String openid = sessionResult.getString("openid");
        String sessionKey = sessionResult.getString("session_key");
        String unionid = sessionResult.getString("unionid");
        
        log.info("=== 微信用户登录成功 ===");
        log.info("openid: {}", openid);
        log.info("session_key: {}", sessionKey);
        log.info("unionid: {}", unionid);
        
        if (loginRequest.getRawData() != null) {
            log.info("用户信息: {}", loginRequest.getRawData());
        }
        
        // 封装返回结果
        WxLoginResponse response = new WxLoginResponse();
        response.setOpenid(openid);
        response.setSessionKey(sessionKey);
        response.setUnionid(unionid);
        
        return response;
    }
    
    /**
     * 获取微信用户信息
     * 
     * @param loginRequest 登录请求参数
     * @return 用户信息
     */
    @Override
    public Object getWxUserInfo(WxLoginRequest loginRequest) {
        log.info("获取微信用户信息请求: {}", loginRequest);
        
        // 这里简单返回前端传递的原始用户信息
        if (loginRequest.getRawData() != null && !loginRequest.getRawData().isEmpty()) {
            JSONObject userInfo = JSONObject.parseObject(loginRequest.getRawData());
            
            // 打印用户信息到控制台（测试用）
            log.info("=== 微信用户信息 ===");
            log.info("昵称: {}", userInfo.getString("nickName"));
            log.info("头像: {}", userInfo.getString("avatarUrl"));
            log.info("性别: {}", userInfo.getIntValue("gender"));
            log.info("国家: {}", userInfo.getString("country"));
            log.info("省份: {}", userInfo.getString("province"));
            log.info("城市: {}", userInfo.getString("city"));
            
            return userInfo;
        }
        
        return null;
    }
    
    /**
     * 获取微信openid
     * 
     * @param code 微信临时登录凭证
     * @return 包含openid和sessionKey的Map
     */
    @Override
    public Map<String, Object> getWxOpenid(String code) {
        log.info("专门获取微信openid的请求, code: {}", code);
        
        Map<String, Object> resultMap = new HashMap<>();
        
        try {
            // 调用微信接口获取openid
            JSONObject sessionResult = wxApiUtils.code2Session(code);
            
            if (sessionResult == null) {
                log.error("获取微信openid失败, code: {}", code);
                resultMap.put("error", "获取微信信息失败");
                return resultMap;
            }
            
            // 检查是否返回了错误码
            Integer errcode = sessionResult.getInteger("errcode");
            if (errcode != null && errcode != 0) {
                String errmsg = sessionResult.getString("errmsg");
                log.error("微信接口返回错误，错误码: {}, 错误信息: {}", errcode, errmsg);
                resultMap.put("error", errmsg);
                resultMap.put("errcode", errcode);
                resultMap.put("errmsg", errmsg);
                
                // 特殊处理code已使用错误
                if (errcode == 40163) {
                    resultMap.put("error", "微信登录凭证已失效，每个凭证只能使用一次，请重新获取");
                }
                
                return resultMap;
            }
            
            String openid = sessionResult.getString("openid");
            String sessionKey = sessionResult.getString("session_key");
            
            if (openid == null || openid.isEmpty()) {
                log.error("获取微信openid为空");
                resultMap.put("error", "获取微信openid为空");
                return resultMap;
            }
            
            log.info("成功获取微信openid: {}", openid);
            
            resultMap.put("openid", openid);
            resultMap.put("sessionKey", sessionKey);
            
            return resultMap;
        } catch (Exception e) {
            log.error("获取微信openid异常", e);
            resultMap.put("error", "获取微信openid异常: " + e.getMessage());
            return resultMap;
        }
    }
    
    /**
     * 微信用户注册
     * 
     * @param registerRequest 注册请求参数
     * @return 注册结果，成功返回用户信息，失败返回错误信息
     */
    @Override
    public Map<String, Object> registerWxUser(WxRegisterRequest registerRequest) {
        log.info("微信用户注册请求开始处理: username={}", registerRequest.getUsername());
        
        Map<String, Object> resultMap = new HashMap<>();
        
        try {
            // 参数校验
            if (StringUtils.isEmpty(registerRequest.getUsername()) || 
                StringUtils.isEmpty(registerRequest.getPassword()) || 
                StringUtils.isEmpty(registerRequest.getConfirmPassword()) || 
                StringUtils.isEmpty(registerRequest.getCode())) {
                
                resultMap.put("error", "注册信息不完整，请填写用户名、密码和确认密码");
                return resultMap;
            }
            
            // 校验密码是否一致
            if (!registerRequest.getPassword().equals(registerRequest.getConfirmPassword())) {
                resultMap.put("error", "两次输入的密码不一致");
                return resultMap;
            }
            
            // 校验用户名长度
            if (registerRequest.getUsername().length() < UserConstants.USERNAME_MIN_LENGTH || 
                registerRequest.getUsername().length() > UserConstants.USERNAME_MAX_LENGTH) {
                resultMap.put("error", "用户名长度必须在2到20个字符之间");
                return resultMap;
            }

            // 校验密码长度
            if (registerRequest.getPassword().length() < UserConstants.PASSWORD_MIN_LENGTH || 
                registerRequest.getPassword().length() > UserConstants.PASSWORD_MAX_LENGTH) {
                resultMap.put("error", "密码长度必须在5到20个字符之间");
                return resultMap;
            }
            
            // 获取微信openid
            Map<String, Object> wxInfo = this.getWxOpenid(registerRequest.getCode());
            if (wxInfo.containsKey("error")) {
                return wxInfo;
            }
            
            String openid = (String) wxInfo.get("openid");
            log.info("微信用户注册获取到openid: {}", openid);
            
            // 检查该微信账号是否已经注册
            SysUser existUser = userService.selectUserByWxOpenid(openid);
            if (existUser != null) {
                log.warn("微信openid已存在，无法重复注册: {}", openid);
                resultMap.put("error", "该微信账号已注册，请直接登录");
                return resultMap;
            }
            
            // 检查用户名是否已经存在
            SysUser checkUser = new SysUser();
            checkUser.setUserName(registerRequest.getUsername());
            if (!userService.checkUserNameUnique(checkUser)) {
                resultMap.put("error", "用户名已存在");
                return resultMap;
            }
            
            // 创建用户
            SysUser user = new SysUser();
            user.setUserName(registerRequest.getUsername());
            user.setNickName(StringUtils.isNotEmpty(registerRequest.getNickName()) ? 
                    registerRequest.getNickName() : registerRequest.getUsername());
            user.setPassword(SecurityUtils.encryptPassword(registerRequest.getPassword()));
            user.setWxOpenid(openid);
            
            // 设置可选信息
            if (StringUtils.isNotEmpty(registerRequest.getAvatar())) {
                user.setAvatar(registerRequest.getAvatar());
            }
            if (StringUtils.isNotEmpty(registerRequest.getPhonenumber())) {
                user.setPhonenumber(registerRequest.getPhonenumber());
            }
            if (StringUtils.isNotEmpty(registerRequest.getEmail())) {
                user.setEmail(registerRequest.getEmail());
            }
            
            // 设置默认状态
            user.setDeptId(110L); // 默认部门ID
            user.setStatus("0");  // 正常状态
            user.setDelFlag("0"); // 未删除
            
            // 注册用户
            boolean result = userService.registerUser(user);
            if (result) {
                log.info("微信用户注册成功: {}, openid: {}", user.getUserName(), openid);
                resultMap.put("success", true);
                resultMap.put("username", user.getUserName());
                resultMap.put("openid", openid);
                return resultMap;
            } else {
                log.error("微信用户注册失败: {}", user.getUserName());
                resultMap.put("error", "注册失败，请稍后重试");
                return resultMap;
            }
        } catch (Exception e) {
            log.error("微信用户注册异常: {}", e.getMessage(), e);
            resultMap.put("error", "注册发生异常: " + e.getMessage());
            return resultMap;
        }
    }
}